package threads

import exceptions.BilibiliException
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.ArrayBlockingQueue
import kotlin.text.StringBuilder

/**
 * 调用B站API的线程
 *
 * @param aidList AV号列表，该线程只负责这个些AV号，需要提前分配好各个线程的AV号
 * @param queue 阻塞队列，用于“生产者-消费者”模式的资源沟通
 * @author Jingyu
 */
class ApiThread(
    private val aidList: MutableList<Int>,
    private val queue: ArrayBlockingQueue<MediaListResponse>
) : Thread() {
    private val logger: Logger = LogManager.getLogger(Main::class.java)

    /**
     * 根据AV号创建URL字符串。该B站API可以在一个URL里存放多个AV号
     */
    private fun buildUrl(): String {
        val stringBuilder = StringBuilder("https://api.bilibili.com/medialist/gateway/base/resource/infos?resources=")
        for (aid in aidList) {
            stringBuilder.append(aid).append(":2,")
        }
        stringBuilder.deleteAt(stringBuilder.length - 1)
        return stringBuilder.toString()
    }


    override fun run() {
        val url = URL(buildUrl())
        val connection = url.openConnection() as HttpURLConnection
        connection.requestMethod = "GET"
        val responseCode = connection.responseCode
        if (responseCode == HttpURLConnection.HTTP_OK) {
            val json = Json {
                ignoreUnknownKeys = true
            }
            val response = connection.inputStream.bufferedReader().use { it.readText() }
            val mediaListResponse = json.decodeFromString<MediaListResponse>(response)
            // 如果B站不给code=200，就要抛出异常，通常是被封IP了之类的原因造成的
            if (mediaListResponse.code != 0) {
                logger.error("B站HTTP请求正确返回，但返回结果异常。Code: ${mediaListResponse.code}")
            }
            queue.put(mediaListResponse) // 把获取到的数据添加到队列之中
            //println(mediaListResponse)
            for (media in mediaListResponse.data) {
               logger.debug("API线程（ID: ${currentThread().id}）成功获取数据：" + media.bvid + media.cnt_info)
            }
        } else {
            logger.error("B站HTTP API状态码异常：${responseCode}")
        }
        connection.disconnect()
    }
}
